package net.ming616.nlp.base.web.struts2.action;

import java.io.Serializable;
import java.util.List;

import net.ming616.nlp.base.service.GenericManager;
import net.ming616.nlp.base.utils.Page;
import net.ming616.nlp.base.utils.ReflectionUtils;

import com.opensymphony.xwork2.Action;

@SuppressWarnings({ "serial" })
public abstract class BaseCRUDAction<M extends GenericManager<T, PK>, T, PK extends Serializable>
		extends AbstractCRUDAction {
	PK id;

	List<T> list;

	M manager;

	protected T model;

	protected Page<T> page;

	public String browse() {
		if (null == page) {
			page = new Page<T>();
		}
		page.setStartRowNumber(this.start);
		page.setLength(this.limit);
		page = this.manager.findPage(page);
		return Action.SUCCESS;
	}

	public PK getId() {
		return id;
	}

	public List<T> getList() {
		return list;
	}

	public M getManager() {
		return manager;
	}

	public T getModel() {
		return model;
	}

	public Page<T> getPage() {
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String load() {
		if (null == this.model) {
			if (null == this.id) {
				try {
					Class<T> clazz = ReflectionUtils.getSuperClassGenricType(
							this.getClass(), 1);
					this.model = (T) clazz.newInstance();
				} catch (InstantiationException e) {
					logger.error(e.getMessage());
				} catch (IllegalAccessException e) {
					logger.error(e.getMessage());
				}
			} else {
				this.model = (T) this.manager.get(this.id);
			}
		}
		return Action.SUCCESS;
	}

	@Override
	public String remove() {
		this.manager.remove(this.id);
		return Action.SUCCESS;
	}

	@Override
	public String save() {
		this.manager.save(this.model);
		return Action.SUCCESS;

	}

	public void setId(PK id) {
		this.id = id;
	}

	public void setList(List<T> list) {
		this.list = list;
	}

	public void setManager(M manager) {
		this.manager = manager;
	}

	public void setModel(T model) {
		this.model = model;
	}

	public void setPage(Page<T> page) {
		this.page = page;
	}

	@Override
	public String update() {
		this.manager.save(this.model);
		return Action.SUCCESS;
	}

}
